<script setup lang="ts">
import CustomNavBar from './components/CustomNavBar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import { getBannerAPI, getCategoriesAPI, getHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/components'
import PageSkeleton from './components/PageSkeleton.vue'

const bannerList = ref<BannerItem[]>([])
const categoryList = ref<CategoryItem[]>([])
const hotList = ref<any>([])
const XtxGuessRef = ref<XtxGuessInstance>()
const isTrigger = ref(false)
const isLoading = ref(false)

const getBannerData = async () => {
  const res = await getBannerAPI()
  bannerList.value = res.result
}

const getCategoreis = async () => {
  const res = await getCategoriesAPI()
  categoryList.value = res.result
}

const getHotData = async () => {
  const res = await getHotAPI()
  hotList.value = res.result
}
// 滚动触底
const onScrollToLower = () => {
  XtxGuessRef.value?.loadMore()
}
// 自定义下拉刷新被触发
const onRefresher = async () => {
  // 开启动画
  isTrigger.value = true
  // 猜你喜欢 - 瀑布流组件里面：重置页码、列表、结束标记
  XtxGuessRef.value?.reset()
  // await getBannerData() // 等这个请求结束后
  // await getCategoreis() // 再发送，然后再等这个请求结束
  // await getHotData() // 再发送，用户等待时间长
  // await XtxGuessRef.value?.loadMore() // 需要先重置组件里的数据，再发送请求
  // 优化：多个请求同时发送
  await Promise.all([getBannerData(), getCategoreis(), getHotData(), XtxGuessRef.value?.loadMore()])
  // 关闭动画
  isTrigger.value = false
}

onLoad(async () => {
  isLoading.value = true
  await Promise.all([getBannerData(), getCategoreis(), getHotData()])
  isLoading.value = false
})
</script>

<template>
  <!-- 首页导航 -->
  <CustomNavBar />
  <scroll-view
    class="scroll-view"
    scroll-y
    enable-back-to-top
    @scrolltolower="onScrollToLower"
    refresher-enabled
    @refresherrefresh="onRefresher"
    :refresher-triggered="isTrigger"
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="XtxGuessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
// 首页样式 微信开发者工具中可以看到页面结构顶层为 page 标签，类似于网页中的 body 标签
// 添加 #app，解决 app 端不会渲染 page 标签的问题
/* ifdef APP-PLUS */
#app,
/* endif */
page {
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;

  .scroll-view {
    flex: 1;
  }
}
</style>
